package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.QSellerShopType;
import com.xinhe.web.entity.SellerShopType;
import com.xinhe.web.reposity.SellerShopTypeRepository;
import com.xinhe.web.util.Snowflake;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;

@Service
public class SellerShopTypeService {
    @Autowired
    private SellerShopTypeRepository sellerShopTypeRepository;

    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;

    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public QueryResults<SellerShopType> pageSellerShopType(String name, int pageNum, int pageSize) {
        QSellerShopType qSellerShopType = QSellerShopType.sellerShopType;
        BooleanBuilder builder = new BooleanBuilder();
        //builder.and(qShop.removed.eq(0));
        if (StringUtils.isNotEmpty(name)) {
            builder.and(qSellerShopType.name.contains(name));
        }
        return queryFactory.select(
                Projections.bean(
                        SellerShopType.class,
                        qSellerShopType.name,
                        qSellerShopType.id
                )
        ).from(qSellerShopType)
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
    }

    public Result delete(Long sellerShopTypeId) {
        sellerShopTypeRepository.deleteById(sellerShopTypeId);
        return Result.ok();
    }

    public Result<SellerShopType> findById(Long sellerShopTypeId) {
        return Result.ok(sellerShopTypeRepository.findById(sellerShopTypeId).get());
    }

    public Result saveModel(Long id, String name, String remark) {
        SellerShopType sellerShopType = new SellerShopType();
        sellerShopType.setId(Snowflake.generateId());
        sellerShopType.setName(name);
        sellerShopTypeRepository.save(sellerShopType);
        return Result.ok();
    }
}